const express = require('express');
const router = express.Router();
const RefundModel = require('../db/RefundModel');
const OrderModel = require('../db/OrderModel');
const RegistrationinforModel = require('../db/RegistrationinforMation');
const UserModel = require('../db/UserModel');//人员表
const moment = require('moment');
const now = () => {
    return moment().format('YYYY-MM-DD HH:mm:ss')
}
/**
 * 退费表
 */

//生成退费单号
function setRefundNumber() {
    let refundId = 'TF' + moment().format('YYYYMMDD') + parseInt(Math.random() * 900000 + 100000);
    return new Promise((resolve, reject) => {
        return RefundModel.findOne({ refundid: refundId }, function (err, res) {
            if (err) {
                reject(err)
            } else {
                resolve(refundId)
            }
        })
    });
}
//生成退费单
router.post('/save', (req, res) => {
    try {
        req.body.chargeschedule = JSON.parse(req.body.chargeschedule);
        req.body.chargeschedule = req.body.chargeschedule.type
    } catch (error) {
        return res.json({
            code: 201,
            mes: "数据格式错误!"
        })
    }
    if (!req.body.orderid || !req.body.refundpayer || !req.body.refundmoney || !req.body.refundoperator || !req.body.chargeschedule) {
        return res.json({
            code: 202,
            mes: '参数错误。'
        });
    } 
    let patientid = req.body.patientid;
    setRefundNumber().then(refundid => {
        req.body.refundid = refundid;
        req.body.refundtime = now()
        const temp = new RefundModel(req.body);

        if (req.body.ordertype.indexOf('挂号费') > -1) {//退挂号费时修改挂号单的支付状态
            return RegistrationinforModel.findOne({ payer: patientid }, ['cureorder']).then(regmodel => {
                if(regmodel){
                    return RegistrationinforModel.update({ payer: patientid }, { $set: { paystate: 3 } }).then(r => {
                        return temp.save().then(result => {
                            return res.json({
                                code: 200,
                                mes: '退款单创建成功。'
                            });
                        });
                    })
                }
                else if (regmodel.cureorder.state == 2 && regmodel) {
                    return res.json({
                        code: 201,
                        mes: '此客户就诊订单未退款，禁止退挂号费！'
                    });
                } 
            })
        } else {
            return temp.save().then(result => {
                return res.json({
                    code: 200,
                    mes: '退款单创建成功。'
                });
            });
        }

    }).catch((err) => {
        return res.json({
            code: 202,
            mes: '产生退费单失败。',
            err
        });
    })

});

function setidname(user, order, refundarr) {
    let tempobj = {};
    for (let i = 0; i < user.length; i++) {
        tempobj[user[i]._id] = user[i];
    }
    for (let i = 0; i < order.length; i++) {
        tempobj[order[i].orderid] = order[i];
    }
    for (let i = 0; i < refundarr.length; i++) {
        refundarr[i].refundoperator_name = tempobj[refundarr[i].refundoperator].name;
        refundarr[i].paytime = tempobj[refundarr[i].orderid].paytime;
    }
    return refundarr;
}
router.get('/find', (req, res) => {
    let pageindex = req.query.pageindex || 1;//页码
    let pagesize = req.query.pagesize || 9;//每页显示数据条数 
    let starttime = req.query.starttime;
    let endtime = req.query.endtime;
    let searchtxt = req.query.searchtxt;
    let refundarr = [];
    let count = '';
    let timearr = [];
    if (!searchtxt && starttime && endtime) {
        //根据时间查询
        RefundModel.count({ refundtime: { $gte: starttime }, refundtime: { $lte: endtime } }).then(count => {
            RefundModel.find({ refundtime: { $gte: starttime }, refundtime: { $lte: endtime } }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).sort({ refundtime: -1 }).lean(true).then(refund => {
                for (let i = 0; i < refund.length; i++) {
                    timearr.push(refund[i].orderid);
                }
                return UserModel.find({}, ['name']).then(user => {
                    return OrderModel.find({ orderid: { $in: timearr } }, ['orderid', 'paytime']).then(order => {
                        refundarr = setidname(user, order, refundarr);//操作人ID对应操作人姓名
                        return res.json({
                            code: 200,
                            mes: '查询成功。',
                            data: refundarr,
                            count: count
                        })
                    })
                })
            }).catch(() => {
                return res.json({
                    code: 201,
                    mes: '查询失败。'
                });
            })
        }).catch(() => {
            return res.json({
                code: 201,
                mes: '意外错误。'
            });
        })

    } else if (searchtxt && !starttime || searchtxt && starttime) {
        let num = /^1[3|4|5|7|8|9][0-9]\d{4,8}$/;//判断是否为手机号
        let chinese = /[\u4e00-\u9fa5]/;//判断是否为汉字
        let letter = /TF/;//判断是否包含TF两个字符
        if (num.test(searchtxt)) {
            //根据手机号查询
            RefundModel.count({ payphone: searchtxt }).then(num => {
                return RefundModel.find({ payphone: searchtxt }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).sort({ refundtime: -1 }).lean(true).then(refund => {
                    for (let i = 0; i < refund.length; i++) {
                        timearr.push(refund[i].orderid);
                    }
                    return UserModel.find({}, ['name']).then(user => {
                        return OrderModel.find({ orderid: { $in: timearr } }, ['orderid', 'paytime']).then(order => {
                            refundarr = setidname(user, order, refund);//操作人ID对应操作人姓名
                            return res.json({
                                code: 200,
                                mes: '查询成功。',
                                data: refundarr,
                                count: num
                            })
                        })

                    })
                })
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '查询失败。'
                });
            })
        }
        else if (chinese.test(searchtxt)) {
            //根据患者姓名查询
            RefundModel.count({ refundpayer: searchtxt }).then(num => {
                return RefundModel.find({ refundpayer: searchtxt }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).sort({ refundtime: -1 }).lean(true).then(refund => {
                    for (let i = 0; i < refund.length; i++) {
                        timearr.push(refund[i].orderid);
                    }
                    return UserModel.find({}, ['name']).then(user => {
                        return OrderModel.find({ orderid: { $in: timearr } }, ['orderid', 'paytime']).then(order => {
                            refundarr = setidname(user, order, refund);//操作人ID对应操作人姓名
                            return res.json({
                                code: 200,
                                mes: '查询成功。',
                                data: refundarr,
                                count: num
                            })
                        })

                    })
                })
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '查询失败。'
                });
            })
        }
        else if (letter.test(searchtxt)) {
            //根据退费单号查询
            RefundModel.count({ refundid: searchtxt }).then(num => {
                return RefundModel.find({ refundid: searchtxt }).skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).sort({ refundtime: -1 }).lean(true).then(refund => {
                    for (let i = 0; i < refund.length; i++) {
                        timearr.push(refund[i].orderid);
                    }
                    return UserModel.find({}, ['name']).then(user => {
                        return OrderModel.find({ orderid: { $in: timearr } }, ['orderid', 'paytime']).then(order => {
                            refundarr = setidname(user, order, refund);//操作人ID对应操作人姓名
                            return res.json({
                                code: 200,
                                mes: '查询成功。',
                                data: refundarr,
                                count: num
                            })
                        })

                    })
                })
            }).catch(err => {
                return res.json({
                    code: 201,
                    mes: '查询失败。'
                });
            })
        } else {
            return res.json({
                code: 201,
                mes: '搜索条件错误，请检查。'
            });
        }
    } else {
        //查询所有退费单
        RefundModel.count().then(num => {
            RefundModel.find().skip(parseInt((pageindex - 1) * pagesize)).limit(parseInt(pagesize)).sort({ refundtime: -1 }).lean(true).then(refund => {
                refundarr = refund;

                for (let i = 0; i < refundarr.length; i++) {
                    timearr.push(refundarr[i].orderid);
                }
                UserModel.find({}, ['name']).then(user => {
                    return OrderModel.find({ orderid: { $in: timearr } }, ['orderid', 'paytime']).then(order => {
                        return refundarr = setidname(user, order, refundarr);//操作人ID对应操作人姓名
                    })
                }).then(refund => {
                    return res.json({
                        code: 200,
                        mes: '查询成功。',
                        data: refund,
                        count: num
                    })
                }).catch(() => {
                    return res.json({
                        code: 201,
                        mes: '查询失败。'
                    });
                })
            }).catch(() => {
                return res.json({
                    code: 201,
                    mes: '查询失败。'
                });
            })
        }).catch(() => {
            return res.json({
                code: 201,
                mes: '查询失败。'
            });
        })
    }
});

module.exports = router;